package com.kuanter.kuanterauto.activity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.alipay.AlipayCenter;
import com.kuanter.kuanterauto.alipay.AlixId;
import com.kuanter.kuanterauto.alipay.BaseHelper;
import com.kuanter.kuanterauto.alipay.MobileSecurePayHelper;
import com.kuanter.kuanterauto.alipay.OrderInfoUtil;
import com.kuanter.kuanterauto.alipay.ResultChecker;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.AccountInfoNew;
import com.kuanter.kuanterauto.entity.OtherAccount;
import com.kuanter.kuanterauto.entity.OtherAccount.Item;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.utils.Utility;
import com.kuanter.kuanterauto.wapalipay.WapPayActivity;
import com.unionpay.UPPayAssistEx;

/** 
 * @author utopia
 * @version 2013-11-4 上午10:18:09
 * 
 */
public class Recharge3Activity extends BaseActivity_NoBar implements Callback{
	List<OtherAccount> accountInfoNewList;  //其他账户，跳转到详情用
	
	private DataLoader dataLoader;
	private String xuNiAccountCardNumber = "";
	public static String XuNiAccountCardNumber = "XuNiAccountCardNumber";
	AlipayCenter alipayCenter;
	/*****************************************************************
     * mMode参数解释：
     *      "00" - 启动银联正式环境
     *      "01" - 连接银联测试环境
     *****************************************************************/
    private String mMode = "00";
    private static final int PLUGIN_VALID = 0;
    private static final int PLUGIN_NOT_INSTALLED = -1;
    private static final int PLUGIN_NEED_UPGRADE = 2;
	
	private void downLoadCardInfos() {
		dataLoader = new DataLoader(this);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//从SharedPreferences本地化数据中区账号信息
		params.add(new BasicNameValuePair("userId",""+SharePrefenceUtil.getUserID(this)));
		Log.i("wuyang", SharePrefenceUtil.getUserID(this)+"");
		dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.QUERY_ACCOUNT_INFO, params, handlerQueryAccountInfo, "", false);
		showProgress("正在加载数据...");
	}

	RadioButton yl_pay;
	RadioButton recharge_app;
	RadioButton re_wapPay;
	
	TextView account_yu_e;
	RelativeLayout rl_account_list_item;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recharge_card);
		mHandler = new Handler(this);
		//注册广播
		IntentFilter filter = new IntentFilter("input");
		myBroadcastReceiver = new MyBroadcastReceiver();
		registerReceiver(myBroadcastReceiver, filter );
		initUI();
		downLoadCardInfos();
	}
	
	@Override
	protected void onResume() {
		if(isChargeSuccess) {
			downLoadCardInfos();
			isChargeSuccess = false;
		}
		super.onResume();
	}

	private OnClickListener itemClick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			if(view.getId() == yl_pay.getId()) {
				recharge_app.setSelected(false);
				yl_pay.setSelected(true);
				re_wapPay.setSelected(false);
			} else if(view.getId() == recharge_app.getId()) {
				recharge_app.setSelected(true);
				yl_pay.setSelected(false);
				re_wapPay.setSelected(false);
			} else if(view.getId() == re_wapPay.getId()) {
				recharge_app.setSelected(false);
				yl_pay.setSelected(false);
				re_wapPay.setSelected(true);
			}
		}
	};
	
	private List<String> strCredits = new ArrayList<String>();
	private void initUI() {
//		strCredits.add("0.01");
		strCredits.add("50");
		strCredits.add("100");
		strCredits.add("200");
		strCredits.add("500");
		strCredits.add("其他金额");
		
		menuWindow = new SelecterGradePopupWindow3(Recharge3Activity.this, new MyPopListViewClick3(),strCredits);
		account_yu_e = (TextView) findViewById(R.id.account_yu_e);
		cz_num = (TextView) findViewById(R.id.cz_num);
		cz_zf = (TextView) findViewById(R.id.cz_zf);
		
		rl_account_list_item = (RelativeLayout) findViewById(R.id.rl_account_list_item);
		rl_account_list_item.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent_info = new Intent(Recharge3Activity.this, AccountBalanceActivity.class);
				String yue = account_yu_e.getText().toString();
				intent_info.putExtra("yue", yue);
				intent_info.putExtra("accountInfoNewList", (Serializable)accountInfoNewList);
				startActivity(intent_info);
			}
		});
		
		yl_pay = (RadioButton) findViewById(R.id.yl_pay);
		yl_pay.setOnClickListener(itemClick);
		recharge_app = (RadioButton) findViewById(R.id.recharge_app);
		recharge_app.setOnClickListener(itemClick);
		re_wapPay = (RadioButton) findViewById(R.id.re_wapPay);
		re_wapPay.setOnClickListener(itemClick);
		final MobileSecurePayHelper msph = new MobileSecurePayHelper(this);
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if(msph.isMobile_spExist()) {
					recharge_app.setSelected(true);
					yl_pay.setSelected(false);
					re_wapPay.setSelected(false);
				} else {
					recharge_app.setSelected(false);
					yl_pay.setSelected(true);
					re_wapPay.setSelected(false);
				}
			}
		});
		
	}

	public void back(View v){
		finish();
	}
	
	boolean isChargeSuccess = false;
	private ProgressDialog mLoadingDialog = null;
	private Handler mHandler = null;
	public void startpay(View view) {
		isChargeSuccess = true;
		if(ProApplication.getInstance().getCardInfoList() != null && ProApplication.getInstance().getCardInfoList().size() > 0){
			ProApplication.getInstance().getCardInfoList().clear();
		}
		SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
		if(yl_pay.isSelected()) {
//			ProApplication.state = "1";
			if(ProApplication.state.equals("0")) {
				showToast("该功能尚未开放，请选择其他方式充值");
				
				//TODO  银联
//				mLoadingDialog = ProgressDialog.show(Recharge3Activity.this, // context 
//	                    "", // title 
//	                    "正在获取交易流水号,请稍候...", // message 
//	                    true);
//				/************************************************* 
//	             * 
//	             *  步骤1：从网络开始,获取交易流水号即TN 
//	             *  
//	             ************************************************/
////	            new Thread(getUnipayNo).start();
//				dataLoader = new DataLoader(this);
//				List<NameValuePair> params = new ArrayList<NameValuePair>();
//				params.add(new BasicNameValuePair("cardNumber",xuNiAccountCardNumber));
//				params.add(new BasicNameValuePair("rechargeAmount",cz_zf.getText().toString().replace("元", "")));
//				params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
//				params.add(new BasicNameValuePair("type", "1"));
//				dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.ORDER, params, mHandler, "", false);
			} else if(ProApplication.state.equals("1")) {
				//TODO  银联
				mLoadingDialog = ProgressDialog.show(Recharge3Activity.this, // context 
	                    "", // title 
	                    "正在获取交易流水号,请稍候...", // message 
	                    true);
				/************************************************* 
	             * 
	             *  步骤1：从网络开始,获取交易流水号即TN 
	             *  
	             ************************************************/
//	            new Thread(getUnipayNo).start();
				dataLoader = new DataLoader(this);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("cardNumber",xuNiAccountCardNumber));
				params.add(new BasicNameValuePair("rechargeAmount",cz_zf.getText().toString().replace("元", "")));
				params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
				params.add(new BasicNameValuePair("type", "1"));
				dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.ORDER, params, mHandler, "", false);
//			startActivity_anim(0);
			} else {
				showToast("该功能尚未开放，请选择其他方式充值");
			}
		} else if(recharge_app.isSelected()) {
			alipayCenter = new AlipayCenter(this); 
			boolean isPrepare = alipayCenter.payPrepareForcheckInstallAlipay();
			if (isPrepare) {
				boolean isCheckForPartnerAndSeller = alipayCenter.checkInfoForPartnerAndSeller();
				if (isCheckForPartnerAndSeller) {
					dataLoader = new DataLoader(Recharge3Activity.this);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("cardNumber",xuNiAccountCardNumber));
					params.add(new BasicNameValuePair("rechargeAmount",cz_zf.getText().toString().replace("元", "")));
					params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
					params.add(new BasicNameValuePair("type", "0"));
					dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.ORDER, params, handlerRechargeAPP, "", false);
					showProgress("请稍等...");
			}
		}
		} else if(re_wapPay.isSelected()) {
			showProgress("请稍等...");
			dataLoader = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cardNumber",xuNiAccountCardNumber));
			params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
			dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.isExistVirtualCardNumber, params, webHandler, "", false);
		}
	}
	
	private SelecterGradePopupWindow3 menuWindow;
	public void toRecharge(View v) {
		menuWindow.showAtLocation(Recharge3Activity.this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(myBroadcastReceiver != null){
			unregisterReceiver(myBroadcastReceiver);
		}
	}

	/**
	 * 请求卡片
	 */
	Handler handlerQueryAccountInfo = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
//				result = Recharge3Activity.this.getResources().getString(R.string.testData); //TODO
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status //
															// 字段值是否为false
							com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
									.parseObject(result);
							if (null != jsonObjectResult.getString("userAccountInfo")) {
								String JsonStringUserAccountInfo = jsonObjectResult.getString("userAccountInfo");
								if (JsonStringUserAccountInfo != null) {
									com.alibaba.fastjson.JSONObject jsonObjectUserAccountInfo = JSON.parseObject(JsonStringUserAccountInfo);
									if(jsonObjectUserAccountInfo != null) {
										// 获取其他账户信息
										String str_ja = jsonObjectUserAccountInfo.getString("newOtherAccountInfo");
										if (str_ja != null) {
											org.json.JSONArray ja = new org.json.JSONArray(str_ja);
											if (ja != null) {
												accountInfoNewList = new ArrayList<OtherAccount>();
												for (int j = 0; j < ja.length(); j++) {
													JSONObject jo_a = ja.optJSONObject(j);
													OtherAccount oa = new OtherAccount();
													String cardNum = jo_a.optString("cardNumber");
													oa.setCardNumber(cardNum);
													Map<String, Integer> map = new HashMap<String, Integer>();
													org.json.JSONArray ja_message = jo_a.optJSONArray("message");
													List<Item> listItem = new ArrayList<OtherAccount.Item>();
													int location = 0;
													if (ja_message != null) {
														for (int m = 0; m < ja_message.length(); m++) {
															JSONObject jo_itme = ja_message.optJSONObject(m);
															String categoryName = jo_itme.optString("categoryName");
															String accountType = jo_itme.optString("accountType");
															String balance = jo_itme.optString("balance");
															if (map.containsKey(categoryName)) {
																int position = map.get(categoryName);
																try {
																	Item item = listItem.get(position);
																	if (item != null) {
																		String b = item.getBalance();
																		Double d1 = Double.valueOf(b);
																		Double d2 = Double.valueOf(balance);
																		Double d = d1 + d2;
																		item.setBalance(d + "");
																	}
																} catch (Exception e) {
																	System.err.println("!@#$$$$$$$");
																}
																
															} else {
																Item item = new OtherAccount.Item();
																item.setAccountType(accountType);
																item.setCategoryName(categoryName);
																item.setBalance(balance);
																listItem.add(item);
																map.put(categoryName,location);
																location++;
															}
															
														}
													}
													oa.setMessage(listItem);
													accountInfoNewList.add(oa);
												}
											}
										}
										
										// accountInfoNewList =
										// JSONArray.parseArray(JsonArrayOtherAccountInfo,
										// OtherAccount.class);
										// JSONArray.parseArray(text, types)
										
										// 获取充值账户信息
										JSONArray JsonArrayreChargeAccountInfo = jsonObjectUserAccountInfo.getJSONArray("rechargeAccountInfo");
										if (JsonArrayreChargeAccountInfo != null) {
											List<AccountInfoNew> ChargeAccountInfoNewList = new ArrayList<AccountInfoNew>();
											for (int i = 0; i < JsonArrayreChargeAccountInfo.size(); i++) {
												AccountInfoNew accountInfoNew = new AccountInfoNew();
												JSONArray JsonArrayChargeAccountInfoIndex = (JSONArray) JsonArrayreChargeAccountInfo.get(i);
												// 数据 值
												accountInfoNew.setNumber(String.valueOf((BigDecimal) JsonArrayChargeAccountInfoIndex.get(0)));
												// 数据 单位
												accountInfoNew.setUnit((String) JsonArrayChargeAccountInfoIndex.get(1));
												// 数据 卡号
												accountInfoNew.setCardNumber((String) JsonArrayChargeAccountInfoIndex.get(2));
												// 数据 消费类型
												accountInfoNew.setConsumptionStyle((String) JsonArrayChargeAccountInfoIndex.get(3));
												ChargeAccountInfoNewList.add(accountInfoNew);
											}
											if (ChargeAccountInfoNewList.size() > 0) {
												for (AccountInfoNew accountInfoNew : ChargeAccountInfoNewList) {
													xuNiAccountCardNumber += accountInfoNew.getCardNumber() + "@";
												}
												xuNiAccountCardNumber = xuNiAccountCardNumber.substring(0,xuNiAccountCardNumber.lastIndexOf("@"));
											} else {
												xuNiAccountCardNumber = "@";
											}
											double jiFen = 0d;
											double cishu = 0;
											for (AccountInfoNew ain : ChargeAccountInfoNewList) {
												if (ain.getUnit().equals("积分")) {
													jiFen += Double.valueOf(ain.getNumber());
													account_yu_e.setText((new DecimalFormat("#0.00").format(jiFen) + "积分"));
												} else if (ain.getUnit().equals("次数")) {
													cishu += Double.valueOf(ain.getNumber());
													account_yu_e.setText((int) cishu + "次数");
												}
											}
										}
									}
								}
							}
						} else {
							// 显示返回数据中 errorMsg 字段值
							showToast("失败");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	
	
	public View inputView;
	public EditText input_jine_et;
	private TextView cz_num;
	private TextView cz_zf;
	public class MyPopListViewClick3 implements OnItemClickListener {

		protected String chooseed_credits;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
				
				if(strCredits.get(position).equals("其他金额")){
					inputView = View.inflate(Recharge3Activity.this, R.layout.input_view, null);
					input_jine_et = (EditText)inputView.findViewById(R.id.input_jine_et);
					AlertDialog.Builder builder = new AlertDialog.Builder(Recharge3Activity.this)
					.setView(inputView)
					.setMessage("请输入充值金额")
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(!input_jine_et.getText().toString().trim().equals("")){
								if(Integer.valueOf(input_jine_et.getText().toString().trim())>=50){
									chooseed_credits = input_jine_et.getText().toString();
									cz_num.setText(input_jine_et.getText().toString() + "积分");
									cz_zf.setText(input_jine_et.getText().toString() + "元");
								}else {
									showToast("最小充值金额为50元"); 
								}
							}else {
								showToast("请输入充值金额");
							}
						}
					}).setNegativeButton("取消", null);
					builder.create().show();
					//发送广播显示输入法
					Intent intent = new Intent("input");
					sendBroadcast(intent);
				}else{
					chooseed_credits = strCredits.get(position);
					cz_num.setText(chooseed_credits + "积分");
					cz_zf.setText(chooseed_credits + "元");
				}
				menuWindow.dismiss();
			}
		}
	
	/**
	 * 弹出框
	 */
	public class SelecterGradePopupWindow3 extends PopupWindow {


		private TextView btn_cancel;
		private View mMenuView;
		
		ListView insuranceview;
		LayoutInflater inflater;
		
		PopInsuranceAdapter adapter;
		
		List<String> ci_pop;

		public SelecterGradePopupWindow3(Activity context,OnItemClickListener itemsOnClick,List<String> ci_pop) {
			super(context);
			this.ci_pop = ci_pop;
			
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mMenuView = inflater.inflate(R.layout.alert_dialog, null);
			btn_cancel = (TextView) mMenuView.findViewById(R.id.btn_cancel);
			//取消按钮
			btn_cancel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//销毁弹出框
					dismiss();
				}
			});
			
			insuranceview = (ListView) mMenuView.findViewById(R.id.insuranceview);
			insuranceview.setOnItemClickListener(itemsOnClick);
			
			adapter = new PopInsuranceAdapter();
			insuranceview.setAdapter(adapter);
			Utility.setListViewHeightBasedOnChildren(insuranceview);
			
			//设置SelectPicPopupWindow的View
			this.setContentView(mMenuView);
			//设置SelectPicPopupWindow弹出窗体的宽
			this.setWidth(LayoutParams.FILL_PARENT);
			//设置SelectPicPopupWindow弹出窗体的高
			this.setHeight(LayoutParams.WRAP_CONTENT);
			//设置SelectPicPopupWindow弹出窗体可点击
			this.setFocusable(true);
			//设置SelectPicPopupWindow弹出窗体动画效果
			this.setAnimationStyle(R.style.AnimBottom);
			//实例化一个ColorDrawable颜色为半透明
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			//设置SelectPicPopupWindow弹出窗体的背景
			this.setBackgroundDrawable(dw);
			//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
			mMenuView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					
					int height = mMenuView.findViewById(R.id.pop_layout).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});

		}
		class PopInsuranceAdapter extends BaseAdapter {
			@Override
			public int getCount() {
				return ci_pop == null ? 0 : ci_pop.size();
			}
			
			@Override
			public Object getItem(int arg0) {
				return ci_pop.get(arg0);
			}
			
			@Override
			public long getItemId(int arg0) {
				return arg0;
			}
			
			@Override
			public View getView(int position, View view, ViewGroup parent) {
				if(view == null) {
					view = inflater.inflate(R.layout.pop_insurance_item, null);
				}
				TextView item_insurance = (TextView) view.findViewById(R.id.item_insurance);
				item_insurance.setText(ci_pop.get(position));
				return view;
			}
			
		}
	}
	
private MyBroadcastReceiver myBroadcastReceiver;
	
	//自定义广播
		private class MyBroadcastReceiver extends BroadcastReceiver{

			@Override
			public void onReceive(Context context, Intent intent) {
				InputMethodManager m = (InputMethodManager)
						Recharge3Activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
	                            m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
			
		}
		
		//客户端支付handler
		Handler handlerRechargeAPP = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case HttpTask.RESULT_OK:
					finishProgress();
					String result = (String) msg.obj;//{"orderNo":"CZ20130524155046","status":true}
					if (!result.equals("网络连接错误")) {
						try {
							if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
																// 字段值是否为false
								com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
										.parseObject(result);
								String orderNo = jsonObjectResult.getString("orderNo");
								//intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber)
//								String orderInfo = OrderInfoUtil.getOrderInfo(orderNo, "宽途卡充值","宽途汽车",cz_zf.getText().toString().replace("元", ""));
								String orderInfo = OrderInfoUtil.getNewOrderInfo(orderNo, "宽途卡充值","宽途汽车",cz_zf.getText().toString().replace("元", ""));
								boolean payResult = alipayCenter.payStart(orderInfo, mHandlerAlipay);
								if(payResult){
									CardAndAccountActivity.flag = 200;
								}else {
									CardAndAccountActivity.flag = 0;
								}
								finishProgress();
							} else {
								finishProgress();
								// 显示返回数据中 errorMsg 字段值
//								showToast("失败");
								showToast("网络错误,请稍后再试!");
							}
						} catch (JSONException e) {
							finishProgress();
							showToast("登录失败");
							e.printStackTrace();
						}
					} else {
						finishProgress();
						showToast("登录失败,网络错误!");
					}
					break;
				case HttpTask.RESULT_ERROR:
					finishProgress();
					showToast("网络错误!");
					break;
				}
			}
		};
		
		// 这里接收支付结果，支付宝手机端同步通知
					private Handler mHandlerAlipay = new Handler() {
						public void handleMessage(Message msg) {
							try {
								String strRet = (String) msg.obj;

								Log.e("wuyang", strRet); // strRet范例：resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}
								switch (msg.what) {
								case AlixId.RQF_PAY: {
									//
									alipayCenter.closeProgress();

									BaseHelper.log("wuyang", strRet);

									// 处理交易结果
									try {
										// 获取交易状态码，具体状态代码请参看文档
										String tradeStatus = "resultStatus={";// 无多大意义
										int imemoStart = strRet.indexOf("resultStatus=");
										imemoStart += tradeStatus.length();
										int imemoEnd = strRet.indexOf("};memo=");
										tradeStatus = strRet.substring(imemoStart, imemoEnd);

										// 先验签通知
										ResultChecker resultChecker = new ResultChecker(strRet);
										int retVal = resultChecker.checkSign();
//										boolean retVal = com.kuanter.kuanterauto.alipay.Result.checkSign(strRet);
										// 验签失败
										if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
//										if (!retVal) {
//											BaseHelper.showDialog(Recharge3Activity.this,"提示",getResources().getString(R.string.check_sign_failed),android.R.drawable.ic_dialog_alert);
											showToast(getResources().getString(R.string.check_sign_failed));
										} else {// 验签成功。验签成功后再判断交易状态码
											if (tradeStatus.equals("9000")){// 判断交易状态码，只有9000表示交易成功
												ProApplication.getInstance().setCardInfoList(null);
//												BaseHelper.showDialog(Recharge3Activity.this, "提示","支付成功",R.drawable.infoicon);
												showToast("支付成功");
												Intent data = new Intent();
//												data.putExtra("chooseed_credits", chooseed_credits);
												setResult(255, data );
											}else{
//												BaseHelper.showDialog(Recharge3Activity.this, "提示","支付失败",R.drawable.infoicon);
												showToast("支付失败");
											}
												
										}

									} catch (Exception e) {
										e.printStackTrace();
										BaseHelper.showDialog(Recharge3Activity.this, "提示", "取消",
												R.drawable.infoicon);
									}
								}
									break;
								}

								super.handleMessage(msg);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};

					//银联支付
					@Override
					public boolean handleMessage(Message msg) {
						Log.e("aaa", " " + "" + msg.obj);
				        if (mLoadingDialog.isShowing()) {
				            mLoadingDialog.dismiss();
				        }
				        String pn = "";
				        String json = (String) msg.obj;
				        if(json != null) {
				        	try {
								JSONObject jo = new JSONObject(json);
								if(StringUtils.isSuccess(json)) {
									pn = jo.optString("tradeNo");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
				        }

				        if (pn == null || (pn.length() == 0)) {
				            AlertDialog.Builder builder = new AlertDialog.Builder(this);
				            builder.setTitle("错误提示");
				            builder.setMessage("网络错误,请稍后再试!");
				            builder.setNegativeButton("确定",
				                    new DialogInterface.OnClickListener() {
				                        @Override
				                        public void onClick(DialogInterface dialog, int which) {
				                            dialog.dismiss();
				                        }
				                    });
				            builder.create().show();
				        } else {
				            /************************************************* 
				             * 
				             *  步骤2：通过银联工具类启动支付插件 
				             *  
				             ************************************************/
				            // mMode参数解释：
				            // 0 - 启动银联正式环境
				            // 1 - 连接银联测试环境
				            int ret = UPPayAssistEx.startPay(this, null, null, pn, mMode);
				            if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
				                // 需要重新安装控件
				                Log.e("aaa", " plugin not found or need upgrade!!!");
				                AlertDialog.Builder builder = new AlertDialog.Builder(this);
				                builder.setTitle("提示");
				                builder.setMessage("完成购买需要安装银联支付控件，是否安装？");
				                builder.setNegativeButton("确定",
				                        new DialogInterface.OnClickListener() {
				                            @Override
				                            public void onClick(DialogInterface dialog,
				                                    int which) {
				                                dialog.dismiss();
				                                Intent intentPlug = new Intent(Intent.ACTION_VIEW);
				                                intentPlug.setData(Uri.parse("http://mobile.unionpay.com/download/securepayplugin"));
				                                startActivity(intentPlug);
				                            }
				                        });

				                builder.setPositiveButton("取消",
				                        new DialogInterface.OnClickListener() {

				                            @Override
				                            public void onClick(DialogInterface dialog,
				                                    int which) {
				                                dialog.dismiss();
				                            }
				                        });
				                builder.create().show();

				            }
				            Log.e("aaa", "" + ret);
				        }
						return false;
					}
					
	//webHandler 
					private Handler webHandler = new Handler(){
						@Override
						public void handleMessage(Message msg) {
							finishProgress();
							String json = (String) msg.obj;
							if(json != null) {
								try {
									JSONObject jo = new JSONObject(json);
									if(StringUtils.isSuccess(json)) {
										String message = jo.optString("message");
										if(message.equals("true")) {
											SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
											// 调用支付接口,支付成功通知服务器页面，支付成功，并将积分设置
											//支付宝网页支付	方法名：cardRecharge/{cardNumber}/{rechargeAmount}/{mobileNumber}/trade		参数名：cardNumber，rechargeAmount，mobileNumber
											Intent intent = new Intent();
											intent.putExtra("cardNumber", xuNiAccountCardNumber);
											intent.putExtra("rechargeAmount", cz_zf.getText().toString().replace("元", ""));
											intent.putExtra("mobileNumber", sp.getString("mobileNumber", "-1"));
											intent.setClass(Recharge3Activity.this, WapPayActivity.class);
											startActivity(intent);
											CardAndAccountActivity.flag = 200;		
										} else {
											showToast("网络错误,请稍后再试!");
										}
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
							super.handleMessage(msg);
						}
					};
					
					@Override
					protected void onActivityResult(int requestCode, int resultCode, Intent data) {
						/************************************************* 
				         * 
				         *  步骤3：处理银联手机支付控件返回的支付结果 
				         *  
				         ************************************************/
				        if (data == null) {
				            return;
				        }

				        String msg = "";
				        /*
				         * 支付控件返回字符串:success、fail、cancel
				         *      分别代表支付成功，支付失败，支付取消
				         */
				        String str = data.getExtras().getString("pay_result");
				        if (str.equalsIgnoreCase("success")) {
				        	CardAndAccountActivity.flag = 200;
				            msg = "支付成功！";
//				            showToast(msg);
//				            finish();
				        } else if (str.equalsIgnoreCase("fail")) {
				            msg = "支付失败！";
				        } else if (str.equalsIgnoreCase("cancel")) {
				            msg = "支付失败,取消了支付";
				        }

				        AlertDialog.Builder builder = new AlertDialog.Builder(this);
				        builder.setTitle("支付结果通知");
				        builder.setMessage(msg);
				        builder.setInverseBackgroundForced(true);
				        //builder.setCustomTitle();
				        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
				            @Override
				            public void onClick(DialogInterface dialog, int which) {
				                dialog.dismiss();
				            }
				        });
//				        builder.create().show();
				        showToast(msg);
						super.onActivityResult(requestCode, resultCode, data);
					}
}
